import React, { useEffect, useState } from "react";
import axios from "axios";
import { debounce } from "debounce";
import type { ColumnsType } from "antd/es/table";
import {
  Table,
  Button,
  Space,
  Modal,
  Row,
  Col,
  Input,
  message as antdMessage,
} from "antd";
import { useLocation, useSearchParams } from "react-router-dom";
import { useSelector } from "react-redux/es/hooks/useSelector";
export interface ListRawState {
  id: string;
  nickname: string;
  tel: number;
  address: string;
  sex: string;
  type: string;
}

const Home: React.FC = () => {
  //
  const role = useSelector((state: any) => state.user.role);
  const location = useLocation();
  // 1. 数据容器
  const [list, setList] = useState<ListRawState[]>([]);
  // 2. 请求方法
  const getList = async () => {
    const resp = await axios.get("/api/list", { params: { q, type } });
    setList(resp.data.data);
  };
  // 3. 副作用函数
  useEffect(() => {
    getList();
    // 高级写法： 依赖数据项
  }, [location]);
  // 6. 当前选中的数据项目id
  const [selectedID, setSelectID] = useState<string[]>([]);
  // 4. 定义列数据
  const columns: ColumnsType<ListRawState> = [
    {
      key: "id",
      title: "ID",
      dataIndex: "id",
    },
    {
      key: "nickname",
      title: "昵称",
      dataIndex: "nickname",
    },
    {
      key: "tel",
      title: "电话",
      dataIndex: "tel",
    },
    {
      key: "address",
      title: "地址",
      dataIndex: "address",
    },
    {
      key: "sex",
      title: "性别",
      dataIndex: "sex",
    },
    {
      key: "type",
      title: "状态",
      dataIndex: "type",
    },
    {
      key: "opration",
      title: (
        <div>
          {selectedID.length === 0 ? (
            "操作"
          ) : (
            <Button
              type="primary"
              danger
              onClick={() => handleDelete(selectedID.join(","))}
            >
              批量删除
            </Button>
          )}
        </div>
      ),
      dataIndex: "id",
      // 自定义列表结构
      render(id: string, raw: ListRawState) {
        return (
          <Space>
            <Button type="primary" onClick={() => openModal(raw)}>
              编辑
            </Button>
            <Button
              type="primary"
              danger
              onClick={() =>
                isClickPromission(() => handleDelete(id), ["admin"])
              }
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];
  // if (role === "admin") {
  //   columns.push();
  // }
  // 5. 定义删除方法
  const handleDelete = (id: string) => {
    // 二次确认
    Modal.confirm({
      title: "警告",
      content: "确认要删除吗？",
      okText: "确认",
      cancelText: "取消",
      async onOk() {
        // 发送删除请求
        await axios.delete("/api/list/" + id);
        // 重新请求列表
        await getList();
      },
    });
  };

  // 7. 弹框状态： 打开还是关闭
  const [isOpen, setIsOpen] = useState(false);
  // 8. 当前弹框的数据状态
  const [editItem, setEditItem] = useState<ListRawState>({
    id: "1",
    nickname: "2",
    tel: 3,
    address: "4",
    sex: "5",
    type: "",
  });
  // 9. 弹框打开和关闭
  const closeModal = () => setIsOpen(false);
  const openModal = (row: ListRawState) => {
    setIsOpen(true);
    setEditItem(row);
  };
  // 10. 确定修改数据
  const modify = async () => {
    const resp = await axios.post(`/api/list/${editItem.id}`, editItem);
    const { code, message } = resp.data;
    if (code === 200) {
      antdMessage.success(message);
      getList();
    }
  };
  // 11. 使用 hooks
  const [searchParams, setSearchParams] = useSearchParams();
  // 12. 获取查询参数
  const q = searchParams.get("q") || "";
  // 13 定义搜索函数: 防抖
  const handleSearch = debounce((value: string) => {
    setSearchParams({
      q: value,
      type,
    });
  }, 400);
  // 14 定义状态数组
  const types = [
    "全部",
    "未发货",
    "已发货",
    "正在派件",
    "已收货",
    "已签收",
    "已拒签",
  ];
  // 15 当前选中的状态
  const type = searchParams.get("type") || "全部";
  // 16
  const isClickPromission = (callback, myRole: string[]) => {
    if (myRole.includes(role)) {
      callback();
    } else {
      antdMessage.error("当前用户权限不足");
    }
  };
  return (
    <div>
      <Input.Search
        defaultValue={q || ""}
        onSearch={(value) => handleSearch(value)}
      ></Input.Search>
      <Row style={{ alignItems: "center", margin: 10 }}>
        <Col span={1}>状态:</Col>
        <Col>
          <Space>
            {types.map((v, i) => {
              return (
                <Button
                  onClick={() => setSearchParams({ type: v, q })}
                  type={v === type ? "primary" : "default"}
                  key={i}
                >
                  {v}
                </Button>
              );
            })}
          </Space>
        </Col>
      </Row>
      <Table
        rowSelection={{
          onChange(selectedRowKeys) {
            setSelectID(selectedRowKeys as string[]);
          },
        }}
        columns={columns}
        dataSource={list}
        rowKey="id"
      ></Table>

      <Modal
        open={isOpen}
        title="编辑"
        cancelText="取消"
        onOk={() => {
          // 关闭弹框
          closeModal();
          // 修改数据
          modify();
        }}
        onCancel={closeModal}
      >
        <Row style={{ alignItems: "center", margin: "10px 0" }}>
          <Col span={2}>ID:</Col>
          <Col span={22}>
            <Input
              disabled
              value={editItem.id}
              onChange={(e) =>
                setEditItem({
                  // 保存原数据
                  ...editItem,
                  // 修改指定数据
                  id: e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
        <Row style={{ alignItems: "center", margin: "10px 0" }}>
          <Col span={2}>昵称:</Col>
          <Col span={22}>
            <Input
              value={editItem.nickname}
              onChange={(e) =>
                setEditItem({
                  // 保存原数据
                  ...editItem,
                  // 修改指定数据
                  nickname: e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
        <Row style={{ alignItems: "center", margin: "10px 0" }}>
          <Col span={2}>电话:</Col>
          <Col span={22}>
            <Input
              value={editItem.tel}
              onChange={(e) =>
                setEditItem({
                  // 保存原数据
                  ...editItem,
                  // 修改指定数据
                  tel: +e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
        <Row style={{ alignItems: "center", margin: "10px 0" }}>
          <Col span={2}>地址:</Col>
          <Col span={22}>
            <Input
              value={editItem.address}
              onChange={(e) =>
                setEditItem({
                  // 保存原数据
                  ...editItem,
                  // 修改指定数据
                  address: e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
        <Row style={{ alignItems: "center", margin: "10px 0" }}>
          <Col span={2}>性别:</Col>
          <Col span={22}>
            <Input
              value={editItem.sex}
              onChange={(e) =>
                setEditItem({
                  // 保存原数据
                  ...editItem,
                  // 修改指定数据
                  sex: e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
      </Modal>
    </div>
  );
};

export default Home;
